package com.eca.emas.daemon;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;

import com.eca.emas.daemon.shared.EMASMailManager;
import com.eca.emas.daemon.shared.Sensor;
import com.eca.emas.daemon.shared.SensorData;

public class WiregateDataHandler {

	public WiregateDataHandler() {
	}

	@SuppressWarnings("deprecation")
	public SensorData getTemperaturDataForSensor(Sensor sensor,
			WiregateServer server) {
		SensorData data = new SensorData();
		if (sensor != null && server != null) {

			data.setLocationID(server.getLocation_id());
			data.setRecordID(0);
			data.setSensor(sensor);

			try {
				URL url = new URL(
						"http://"
								+ server.getHostOrIP()
								+ "/graph.pl?--start=-1h;--end=now&DEF:ds0=/var/www/rrd/"
								+ sensor.getSensorID() + "_temp.rrd:value:AVERAGE&XPORT:ds0");
				URLConnection connection = url.openConnection();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(connection.getInputStream()));
				String line = "";
				String lastLine = "";
				while ((line = reader.readLine()) != null) {
					lastLine = line;
				}

				if (!lastLine.isEmpty()) {
					Date date = Date.valueOf(lastLine.substring(0,
							lastLine.indexOf(" ")));
					Time time = Time.valueOf(lastLine.substring(
							(lastLine.indexOf(" ") + 1), lastLine.indexOf(";"))
							+ ":00");
					float temp = Float.valueOf(lastLine.substring(
							lastLine.indexOf(";") + 1, lastLine.length())
							.replace(',', '.'));
					
					Timestamp timestamp = new Timestamp(date.getTime());
					timestamp.setHours(time.getHours());
					timestamp.setMinutes(time.getMinutes());
					timestamp.setSeconds(time.getSeconds());

					data.setTimestamp(timestamp);
					data.setAvgTemp(temp);
				}

			} catch (MalformedURLException e) {
				EMASMailManager.getInstance().sendExceptionToAllRecipients(e);
				e.printStackTrace();
			} catch (IOException e) {
				EMASMailManager.getInstance().sendErrorMessageToAllRecipients(EMASMailManager.ERROR_WIREGATE, e);
				WiregateManager.getInstance().removeServer(server);
				e.printStackTrace();
			}
		}
		
		return data;
	}
}
